package com.study.springboot2.listener;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Properties;

//SpringApplicationRunListener接口规定了SpringBoot的生命周期，在各个生命周期广播相应的事件，调用实际的ApplicationListener类。
public class MyApplicatonEnvironListener implements SpringApplicationRunListener {
    private final SpringApplication application;

    private final String[] args;

    private final SimpleApplicationEventMulticaster initialMulticaster;

    public MyApplicatonEnvironListener(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
        this.initialMulticaster = new SimpleApplicationEventMulticaster();
        for (ApplicationListener<?> listener : application.getListeners()) {
            this.initialMulticaster.addApplicationListener(listener);
        }
    }

    // 在run()方法开始执行时，该方法就立即被调用，可用于在初始化最早期时做一些工作
    public void starting() {
        System.out.println("starting>>>>>>>>>>");
    }
    // 当environment构建完成，ApplicationContext创建之前，该方法被调用
    public void environmentPrepared(ConfigurableEnvironment environment) {
        Properties properties = new Properties();
        try {
            // 1. 读取我们的my.properties文件
            properties.load(this.getClass().getClassLoader().
                    getResourceAsStream("my.properties"));
            // 2. 读取名称名称为my
            PropertySource propertySource = new
                    PropertiesPropertySource("my", properties);
            //3. 将资源添加到项目中
            MutablePropertySources propertySources = environment.getPropertySources();
            propertySources.addLast(propertySource);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    // 当ApplicationContext构建完成时，该方法被调用
    public void contextPrepared(ConfigurableApplicationContext context) {

    }
    // 在ApplicationContext完成加载，但没有被刷新前，该方法被调用
    public void contextLoaded(ConfigurableApplicationContext context) {

    }
    // 在ApplicationContext刷新并启动后，CommandLineRunners和ApplicationRunner未被调用前，该方法被调用
    public void started(ConfigurableApplicationContext context) {

    }
    // 在run()方法执行完成前该方法被调用
    public void running(ConfigurableApplicationContext context) {

    }
    // 当应用运行出错时该方法被调用
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }

}
